//
//  JVPharosNetworkModel.m
//  iosframework
//
//  Created by zyma on 2017/8/8.
//  Copyright © 2017年 ljs. All rights reserved.
//

/**
 {
 "v": 1, // 接口版本，现在为1
 "ut": 1484536179728, // 批量上传的时间戳，毫秒
 "app": "lufax", // 应用名称(长度不超过20个字符)
 "cid": "client id" // client id
 "av": "3.3.7", // APP 版本（非中文）
 "p": "ios", // 平台，比如 android，ios 等，英文
 "pv": "ios10.1", // 平台版本，比如 ios10.1 等，英文
 "d": "apple", // 设备名称，比如 apple，英文
 "dv": "iphone7s" // 具体的手机型号，比如 iphone7s，英文
 "l": [{
 "type": "request",
 "t": 1484536179728, // 请求发起的时间，时间戳，毫秒
 "url": "url", // URL，非动态保证（长度不超过500个字符）
 "rid": "request id", // 请求id，随机码32位
 "np": "network protocols(2G, 3G, 4G, wifi)", // 网络协议，英文
 "nc": "0"// 编码，0为非直连非keep-alive，1为直连非 keep-alive，2为非直连keep-alive，3为直连keep-alive
 "ng": "0" // gzip 是否开启，0为未开启，1为开启
 "hc": "http return code(XXX)", // HTTP 返回码
 "bc": "business return code(XXXX)", // 业务返回码
 "pt": "response time in milliseconds", // 完成一次请求总的耗时(ms)
 "qs": "request size(byte)", // 请求的包大小(byte)
 "ps": "response size(byte)", // 响应的包大小(byte)
 "tp": { // 时间相关
 "dns": "dns(ms)", // dns 耗时
 "tcp": "tcp(ms)", // tcp 耗时
 "ssl": "ssl(ms)", // ssl 耗时
 "rq": "request(ms)", // request 耗时
 "rp": "response(ms)", // response 耗时
 "ttfb": "ttfb(ms)", // 读取页面第一个字节的时间
 "ws": "white screen(ms)", // 白屏时间，也就是开始解析DOM耗时，用户在没有滚动时候看到的内容渲染完成并且可以交互的时间
 "fs": "first screen(ms)" // 首屏时间，用户在没有滚动时候看到的内容渲染完成并且可以交互的时间，记录载入时间最长的图片
 },
 "d": "data"
 }]
 }
 */

#import "JVPharosNetworkModel.h"
//#import "JVHttpRequestProtocol.h"
#import <sys/time.h>
//#import "LuCommonConstants.h"
#import "JVMonitorConfig.h"

@interface JVPharosNetworkModel ()

@end

@implementation JVPharosNetworkModel

- (instancetype)init
{
    self = [super init];
    if (self) {
        self.nc = 0;
        self.ng = 0; //mapp接口的content-encoding
    }
    return self;
}

+ (JVPharosNetworkModel *)generatePharosItemModel:(id)requestModel{
    JVPharosNetworkModel *itemModel = [JVPharosNetworkModel new];
    itemModel.type = @"request";
//    itemModel.t = (uint64_t)([[requestModel startTime] timeIntervalSince1970]*NSEC_PER_USEC);
//    itemModel.rid = [requestModel requestID];
//    itemModel.pt = [requestModel responseTime];
    
    if ([[[UIDevice currentDevice] systemVersion] floatValue] > 10.0 ||
        [[[UIDevice currentDevice] systemVersion] floatValue] == 10.0) {
        NSDictionary *transactionMetrics = [requestModel transactionMetrics];
        if (transactionMetrics && [transactionMetrics isKindOfClass:[NSDictionary class]]) {
            itemModel.dns = [[transactionMetrics objectForKey:@"domainLookupTime"] doubleValue];
            itemModel.tcp = [[transactionMetrics objectForKey:@"tcpTime"] doubleValue];
            itemModel.ssl = [[transactionMetrics objectForKey:@"sslTime"] doubleValue];
            itemModel.rq = [[transactionMetrics objectForKey:@"requestTime"] doubleValue];
            itemModel.rp = [[transactionMetrics objectForKey:@"responseTime"] doubleValue];
            itemModel.ttfb = [[transactionMetrics objectForKey:@"firstByteTime"] doubleValue];
        }
    }else {
        itemModel.dns = 0.0;
        itemModel.tcp = 0.0;
        itemModel.ssl = 0.0;
        itemModel.rq = 0.0;
        itemModel.rp = 0.0;
        itemModel.ttfb = 0.0;
    }
    return itemModel;
}


- (NSDictionary *)pharosModeToDic {
    //目前可能的负数是-1，针对endDate和startDate为nil的情况，不需要转换为毫秒
    NSMutableDictionary *pharosModel_dic = [NSMutableDictionary new];
    NSDictionary *tp_dic = @{@"dns":[NSNumber numberWithInteger:(NSInteger)((self.dns<0)?self.dns:self.dns*NSEC_PER_USEC)]?:@"",
                             @"tcp":[NSNumber numberWithInteger:(NSInteger)((self.tcp<0)?self.tcp:self.tcp*NSEC_PER_USEC)]?:@"",
                             @"ssl":[NSNumber numberWithInteger:(NSInteger)((self.ssl<0)?self.ssl:self.ssl*NSEC_PER_USEC)]?:@"",
                             @"rq":[NSNumber numberWithInteger:(NSInteger)(self.rq*NSEC_PER_USEC)]?:@"",
                             @"rp":[NSNumber numberWithInteger:(NSInteger)(self.rp*NSEC_PER_USEC)]?:@"",
                             @"ttfb":[NSNumber numberWithInteger:(NSInteger)(self.ttfb*NSEC_PER_USEC)]?:@""};
    
    // 获取域名和scheme
    NSString *domain = @"";
    if (self.url_obj && [self.url_obj isKindOfClass:[NSURL class]]) {
        domain = [NSString stringWithFormat:@"%@://%@",[self.url_obj scheme],[self.url_obj host]];
    }
    NSString *baseUrl = [domain stringByAppendingString:self.url];
    // Test使用 测试IP直连的commandID后面加标签，便于区分，实际发请求不会有这个
    /**
     if (self.nc == 2) {
     baseUrl = [baseUrl stringByAppendingString:@"_"];
     }else if (self.nc == 3) {
     baseUrl = [baseUrl stringByAppendingString:@"__"];
     }
     **/
    
    pharosModel_dic = [@{@"t":self.t?:@"",
                        @"url":baseUrl?:@"",
                        @"rid":[self.rid UUIDString]?:@"",
                        @"np":@"",
                        @"nc":@(self.nc)?:@"",
                        @"ne":self.ne?:@"",
                        @"ct":self.ct?:@"",
                        @"ng":@(self.ng)?:@"",
                        @"hc":self.hc?:@"",
                        @"bc":self.bc?:@"",
                        @"pt":[NSNumber numberWithInteger:(NSInteger)(self.pt*NSEC_PER_USEC)]?:@"",
                        @"qs":@(self.qs)?:@"",
                        @"ps":@(self.ps)?:@"",
                        @"tp":tp_dic?:@"",
                        @"type":self.type?:@""
                        } mutableCopy];
    if (self.retry != nil && [self.retry length] > 0) {
        
        NSSet *successCode = [[JVMonitorConfig sharedInstance].monitorConfigDelegate httpSuccessCodes];
        
        if (self.hc!=nil && [successCode containsObject:self.hc] && self.retryCount==1) {
            // 第一次就成功的不打点
        } else {
            [pharosModel_dic setValue:@{
                                        @"retry":self.retry?:@"",
                                        @"count":@(self.retryCount)?:@(0)
                                        } forKey:@"p"];
        }
    }
    return pharosModel_dic;
}

- (NSString *)commandId{
    return self.url;
}

@end

